import java.util.Stack;

/**
 * LCR 036. 逆波兰表达式求值
 * https://leetcode.cn/problems/8Zf90G/description/
 */
class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        int n = tokens.length;

        for(int i = 0; i < n; i++) {
            if(!tokens[i].equals("+") && !tokens[i].equals("-")  
                && !tokens[i].equals("*")  && !tokens[i].equals("/") ) {
                // 遇到了数字
                stack.push(Integer.parseInt(tokens[i]));
            } else {
                // 遇到了运算符
                int b = stack.pop();
                int a = stack.pop();
                if(tokens[i].equals("+")) {
                    stack.push(a + b);
                } else if(tokens[i].equals("-")) {
                    stack.push(a - b);
                }else if(tokens[i].equals("*")) {
                    stack.push(a * b);
                }else {
                    stack.push(a / b);
                }
            }
        }

        return stack.pop();
    }
}